package com.cwf.system.controller;


import com.cwf.common.core.controller.BaseController;
import com.cwf.common.entity.http.R;
import com.cwf.common.enums.IsDeleteEnum;
import com.cwf.framework.aspectj.annotation.MyPage;
import com.cwf.security.dao.PermissionListDao;
import com.cwf.security.entity.Permission;
import com.cwf.system.dao.RoleDao;
import com.cwf.system.entity.Role;
import com.cwf.system.service.RolePermissionRelationService;
import com.cwf.system.service.RoleService;
import com.cwf.system.validation.role.AllotRolePermissionParams;
import com.cwf.system.vo.PermissionTreeVO;
import com.cwf.system.vo.RoleInfoVO;
import com.cwf.system.vo.RolePageListVO;
import com.cwf.system.vo.ValidGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;


@SuppressWarnings("all")
@RequestMapping("/system/role")
@RestController
@Valid
public class RoleController extends BaseController {




    @Autowired
    RoleDao roleDao;

    @Autowired
    RoleService roleService;


    @Autowired
    RolePermissionRelationService rolePermissionRelationService;

    @Autowired
    PermissionListDao permissionListDao;

    /**
     * 用户查询和分页
     * @param role
     * @return
     */
    @MyPage
    @GetMapping("/page/list")
    public R pageList(Role role){
        return  R.success(roleService.searchUser(role));
    }

    /**
     * 获取当前角色详情
     * @param id
     * @return
     */
    @GetMapping("/get/info/{id}")
    public R byIdGetRoleInfo(@PathVariable @NotNull Long id){
        return R.success(RoleInfoVO.toRoleInfoVO(roleService.byIdGetRoleInfo(id)));
    }



    /**
     * 修改角色
     * @param role
     */
    @PutMapping("/update")
    public R updateUser(@Validated(value = ValidGroup.Crud.Update.class) @RequestBody Role role){
        String userId = getUserId();

        Role build = Role.builder()
                .roleId(role.getRoleId())
                .roleName(role.getRoleName())
                .roleDesc(role.getRoleDesc())
                .state(role.getState())
                .build();

        return R.update(roleService.updateUser(build));
    }

    /**
     * 添加角色
     * @param role
     */
    @PostMapping("/save/role")
    public  R saveUser(@RequestBody
                           @Validated(value = ValidGroup.Crud.Create.class)
                                   Role role){
        String userId = getUserId();

        Role build = Role.builder()
                .creatorId(Long.valueOf(userId))
                .editUserId(Long.valueOf(userId))
                .roleName(role.getRoleName())
                .roleDesc(role.getRoleDesc()).build();

        return R.insert(roleService.saveUser(build));
    }

    /**
     * 删除角色
     * @param roleId
     */
    @DeleteMapping("/delete/{id}")
    public R deleteUser(@PathVariable Long roleId){
        Role build = Role.builder().roleId(roleId).isDelete(IsDeleteEnum.OK.getCode()).build();
        return R.delete(roleService.deleteUser(build));
    }




    /**
     * 获取角色权限树结构
     * @param roleId 角色id
     */
    @GetMapping("/permission/tree")
    public R<List<PermissionTreeVO>> getRolePermissionTree(
            @RequestParam @NotNull Long roleId
    ){
        return R.success(rolePermissionRelationService.getRolePermissionTree(roleId));
    }

    /**
     * 获取当前角色权限id列表
     * @param roleId 角色id
     */
    @GetMapping("/permission/id/list")
    public R<List<Long>> getRolePermissionIdList(
            @RequestParam @NotNull Long roleId
    ){
        return R.success(rolePermissionRelationService.getRolePermissionIdList(roleId));
    }


    /**
     * 分配角色权限
     * @param params
     */
    @PostMapping("/allot/role/permission")
    public R allotPermission(@RequestBody AllotRolePermissionParams params){
        if (params.getAddIdList().size() ==0 && params.getDeleteIdList().size()==0){
            return R.update(false).writeMsg("至少添加或取消一个权限");
        }

        //去重
        params.setAddIdList(params.getAddIdList().stream().distinct().collect(Collectors.toList()));
        params.setDeleteIdList(params.getDeleteIdList().stream().distinct().collect(Collectors.toList()));

        return R.update(rolePermissionRelationService.allotRolePermission(params));
    }

    /**
     * (前端tree组件)获取当前角色树结构勾选节点
     * @param id 角色id
     */
    @GetMapping("/get/select/tree/{id}")
    public R test(@PathVariable @NotNull Long id) {
        return R.success(rolePermissionRelationService.treeSelect(id));
    }


    @PreAuthorize("hasAuthority('sys:dictionary:delete:query')")
    @GetMapping("/test")
    public R test1() {

        List<Permission> permissions = permissionListDao.accessList("3");
        List<String> collect = permissions.stream().filter(v -> {
            return v.getCategory() == 3;
        }).map(v -> v.getMark()).collect(Collectors.toList());

        return R.success(collect);
    }


}
